import axios from 'axios';
import Cookies from 'js-cookie';
import qs from 'qs';
import _ from 'lodash';
import router from "../router";

export function request(config) {
    const instance = axios.create({
             baseURL: 'http://localhost:8088/wms/',
             //baseURL: 'http://10.49.23.100:8080/wms/',
            timeout: 50000,
            headers: {
                'Content-Type': "application/json;charset=utf-8",
                'Access-Control-Allow-Credentials': "true"
            },
            withCredentials: true

        }
    )
    //请求拦截

    instance.interceptors.request.use(config => {
        config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN';
        // 默认参数
        var defaults = {};
        // 防止缓存，GET请求默认带_t参数
        if (config.method === 'get') {
            config.params = _.merge({}, config.params, {'_t': new Date().getTime()});
        }
        if (_.isPlainObject(config.params)) {
          //  config.params = _.merge({}, defaults, config.params);
			config.paramsSerializer = function(params) {
			          return qs.stringify(params, { arrayFormat: 'repeat' })
			        }
        }
        if (_.isPlainObject(config.data)) {
            config.data = _.merge({}, defaults, config.data);
            if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
                config.data = Qs.stringify(config.data);
            }
        }
        return config;
    }, err => {
        return Promise.reject(err);
    })

    // 相应拦截
    instance.interceptors.response.use(res => {
        if (res.data.code === 401) {
            router.push('login')
            /*win.location.href = 'login.html';*/
            return Promise.reject(res.data.msg);
        }
        let url = res.config.url;

        if (url.indexOf('export') > 0) {
            return res;
        } else
            return res.data;
    }, err => {
        console.error(err);
        if(err.message='Network Error'){
            alert('登录异常，请重新登录')
            router.push('/login')
        }

        return Promise.reject(err);
    })

    return instance(config);
}

